package com.cnzhy.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * ActiveMQ中的生产者(Producer)
 *
 * @author dengp
 */
public class TopicProducer {

    public void sendhello2ActiveMq(String messageText) {
        TopicSession session = null;
        TopicConnection conn = null;
        try {
            TopicConnectionFactory factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://www.zhaoyan5.com:61616");
            conn = factory.createTopicConnection();
            conn.start();
            session = conn.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
            // 创建消息队列
            Topic topic = session.createTopic("test-topic");
            // 创建消息发送者
            TopicPublisher publisher = session.createPublisher(topic);
            // 设置持久化模式 NON_PERSISTENT不开启  PERSISTENT 开启 默认是开启
            publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            MapMessage mapMessage = session.createMapMessage();
            mapMessage.setString("name", "烤鸭");
            mapMessage.setString("address", "深圳");
            publisher.send(mapMessage);
            // 提交会话
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("访问ActiveMQ服务发生错误!!");
        } finally {
            try {
                // 回收会话资源
                if (null != session) session.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
            try {
                // 回收链接资源
                if (null != conn) conn.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
